//
//  myIndentifyController.m
//  SSSAllRollAgency
//
//  Created by Darker on 2017/3/15.
//  Copyright © 2017年 Darker. All rights reserved.
//

#import "myIndentifyController.h"
#import <AVFoundation/AVFoundation.h>
#import <AFNetworking/AFNetworking.h>

@interface myIndentifyController ()<UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

{
    
    UIButton *_fontBtn;
    UIButton *_backBtn;
    UIImageView *_fontImageView;
    UIImageView *_backImageView;
    UILabel *_fontLabel;
    UILabel *_backLabel;
    
    UIImage *fontImage;
    UIImage *backImage;
    //两张照片标识
    int i;
}
/** <#注释#> */
@property (nonatomic, strong) AFHTTPSessionManager *manager;

@end

@implementation myIndentifyController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.title = @"绑定身份证";
    //去掉透明后导航栏下边的黑边
    //    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
    self.navigationController.navigationBar.hidden = NO;
    self.view.backgroundColor = [UIColor colorWithHex:@"F9F9FA"];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //设置界面
    [self setUpApperance];
    
}
#pragma mark - 设置界面
- (void)setUpApperance{

    _fontImageView = [[UIImageView alloc]init];
    [self.view addSubview:_fontImageView];
    _fontImageView.userInteractionEnabled = YES;
    _fontImageView.image = [UIImage imageNamed:@"pic_bg_front"];
    //_fontImageView.backgroundColor = [UIColor yellowColor];
    _fontImageView.sd_layout
    .topSpaceToView(self.view,64 + HeigthIos6CompeteWithCurrent(10))
    .leftSpaceToView(self.view,WidthIos6CompeteWithCurrent(29))
    .rightSpaceToView(self.view,WidthIos6CompeteWithCurrent(29))
    .heightIs(HeigthIos6CompeteWithCurrent(187));
    
    //按钮
    _fontBtn = [[UIButton alloc]init];
    [_fontImageView addSubview:_fontBtn];
    [_fontBtn addTarget:self action:@selector(fontBtnClick) forControlEvents:UIControlEventTouchDown];
    [_fontBtn setBackgroundImage:[UIImage imageNamed:@"icon_additional@2x"] forState:UIControlStateNormal];
    _fontBtn.sd_layout
    .centerYEqualToView(_fontImageView)
    .centerXEqualToView(_fontImageView)
    .heightIs(HeigthIos6CompeteWithCurrent(60))
    .widthIs(WidthIos6CompeteWithCurrent(60));
    _fontBtn.layer.cornerRadius = _fontBtn.frame.size.height/2;
    _fontBtn.layer.masksToBounds = YES;
    
    _fontLabel = [[UILabel alloc]init];
    _fontLabel.text = @"点击长传身份证正面";
    _fontLabel.textColor = [UIColor colorWithHex:@"6D6D6D"];
    _fontLabel.font = [SSSFont systemFontOfSize:15];
    _fontLabel.textAlignment = NSTextAlignmentCenter;
    [_fontImageView addSubview:_fontLabel];
    _fontLabel.sd_layout
    .centerXEqualToView(_fontImageView)
    .topSpaceToView(_fontBtn,HeigthIos6CompeteWithCurrent(28))
    .widthIs(WidthIos6CompeteWithCurrent(200))
    .heightIs(HeigthIos6CompeteWithCurrent(20));
    
    
    _backImageView = [[UIImageView alloc]init];
    [self.view addSubview:_backImageView];
    _backImageView.userInteractionEnabled = YES;
    _backImageView.image = [UIImage imageNamed:@"pic_bg_backside"];
    //_backImageView.backgroundColor = [UIColor redColor];
    _backImageView.sd_layout
    .topSpaceToView(_fontImageView,HeigthIos6CompeteWithCurrent(10))
    .leftSpaceToView(self.view,WidthIos6CompeteWithCurrent(29))
    .rightSpaceToView(self.view,WidthIos6CompeteWithCurrent(29))
    .heightIs(HeigthIos6CompeteWithCurrent(187));
    
    _backBtn = [[UIButton alloc]init];
    [_backImageView addSubview:_backBtn];
    [_backBtn setBackgroundImage:[UIImage imageNamed:@"icon_additional@2x"] forState:UIControlStateNormal];
    [_backBtn addTarget:self action:@selector(backBtnClick) forControlEvents:UIControlEventTouchDown];
    _backBtn.sd_layout
    .centerYEqualToView(_backImageView)
    .centerXEqualToView(_backImageView)
    .heightIs(HeigthIos6CompeteWithCurrent(60))
    .widthIs(WidthIos6CompeteWithCurrent(60));
    _fontBtn.layer.cornerRadius = _fontBtn.frame.size.height/2;
    _fontBtn.layer.masksToBounds = YES;
    
    _backLabel = [[UILabel alloc]init];
    _backLabel.text = @"点击长传身份证反面";
    _backLabel.textColor = [UIColor colorWithHex:@"6D6D6D"];
    _backLabel.font = [SSSFont systemFontOfSize:15];
    _backLabel.textAlignment = NSTextAlignmentCenter;
    [_backImageView addSubview:_backLabel];
    _backLabel.sd_layout
    .centerXEqualToView(_backImageView)
    .topSpaceToView(_fontBtn,HeigthIos6CompeteWithCurrent(28))
    .widthIs(WidthIos6CompeteWithCurrent(200))
    .heightIs(HeigthIos6CompeteWithCurrent(20));
    
    
    //下方背景
    UIView *bottomBgView = [[UIView alloc]init];
    bottomBgView.backgroundColor = [UIColor colorWithHex:@"F9F9FA"];
    [self.view addSubview:bottomBgView];
    bottomBgView.sd_layout
    .topSpaceToView(_backImageView,HeigthIos6CompeteWithCurrent(10))
    .bottomSpaceToView(self.view,0)
    .leftEqualToView(self.view)
    .rightEqualToView(self.view);
    
    //开始绑定按钮
    UIButton *bindingBtn = [[UIButton alloc]init];
    [bindingBtn setTitle:@"开 始 绑 定" forState:UIControlStateNormal];
    [bindingBtn setBackgroundColor:[UIColor colorWithHex:@"46B77D"]];
    [bindingBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    bindingBtn.layer.cornerRadius = 10;
    bindingBtn.layer.masksToBounds = YES;
    [bindingBtn addTarget:self action:@selector(bindingBenClick) forControlEvents:UIControlEventTouchDown];
    [bottomBgView addSubview:bindingBtn];
    bindingBtn.sd_layout
    .topSpaceToView(bottomBgView,HeigthIos6CompeteWithCurrent(21))
    .rightSpaceToView(bottomBgView,WidthIos6CompeteWithCurrent(43))
    .leftSpaceToView(bottomBgView,WidthIos6CompeteWithCurrent(43))
    .heightIs(HeigthIos6CompeteWithCurrent(51));
    
    UIImageView *hintImageView = [[UIImageView alloc]init];
    hintImageView.image = [UIImage imageNamed:@"icon_description"];
    [bottomBgView addSubview:hintImageView];
    hintImageView.sd_layout
    .topSpaceToView(bindingBtn,HeigthIos6CompeteWithCurrent(26))
    .leftSpaceToView(bottomBgView,WidthIos6CompeteWithCurrent(25))
    .heightIs(HeigthIos6CompeteWithCurrent(18))
    .widthIs(WidthIos6CompeteWithCurrent(18));
    
    UILabel *descLabel = [[UILabel alloc]init];
    descLabel.textColor = [UIColor colorWithHex:@"6D6D6D"];
    descLabel.text = @"1、上传的身份证必须清晰\n2、请保证身份证在有效期之内\n3、身份证必须上传正反两面";
    descLabel.font = [SSSFont systemFontOfSize:14];
    descLabel.textAlignment = NSTextAlignmentLeft;
    [bottomBgView addSubview:descLabel];
    descLabel.sd_layout
    .topEqualToView(hintImageView)
    .leftSpaceToView(hintImageView,WidthIos6CompeteWithCurrent(10))
    .autoHeightRatio(0)
    .widthIs(WidthIos6CompeteWithCurrent(200));
}
- (void)fontBtnClick{
    
    i = 1;
    UIActionSheet * sheet = [[UIActionSheet alloc]initWithTitle:@"请选择" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"相册" otherButtonTitles:@"相机", nil];
    [sheet showInView:self.view];
//    [self ZDActionSheetWithTitle:@"青选择" message:nil destructive:@"相机" destructiveAction:^(NSInteger index) {
//        
//        
//    } andOthers:@[@"取消",@"相册"] animated:YES action:^(NSInteger index) {
//        
//        
//        if (index == 0) {
//            
//            
//            
//        }
//        
//    }];
    
}
- (void)backBtnClick{
    i = 2;
    UIActionSheet * sheet = [[UIActionSheet alloc]initWithTitle:@"请选择" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"相册" otherButtonTitles:@"相机", nil];
    [sheet showInView:self.view];
    
}
#pragma mark - ActionSheet代理方法
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex)
    {
        case 0:
        {
            [self getImage:0];
            
        }
            break;
        case 1:
        {
            [self getImage:1];
        }
            break;
            
        default:
            break;
    }
}
#pragma mark - 调用相机或者是相册
- (void)getImage:(int)sender
{
    NSUInteger sourceType = 0;
    switch (sender)
    {
        case 0:
            // 照片
            sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            break;
        case 1:
        {
            // 相机
            
            NSString *mediaType = AVMediaTypeVideo;
            AVAuthorizationStatus authStatus =[AVCaptureDevice authorizationStatusForMediaType:mediaType];
            if (authStatus ==  AVAuthorizationStatusDenied)
            {
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wdeprecated-declarations"
                UIAlertView * alertView=[[UIAlertView alloc]initWithTitle:@"" message:@"请在iPhone的“设置-隐私-相机”选项中,允许demo访问您的相机" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
#pragma clang diagnostic pop
                [alertView show];
                return;
            }
            else
            {
                if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
                {
                    sourceType = UIImagePickerControllerSourceTypeCamera;
                    break;
                }
            }
            
        }
        default:
            break;
    }
    // 跳转到相机或相册页面
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = sourceType;
    [self presentViewController:picker animated:YES completion:nil];
    
}
#pragma mark - 相机调用完成之后拿到相片
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    if (i == 1) {
        
        UIImage * image1 = [info objectForKey:UIImagePickerControllerEditedImage];
        
        _fontImageView.image = image1;
        //_fontImageView
       fontImage = image1;
        
        [_fontBtn setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
        _fontLabel.hidden = YES;
        
    }else if(i == 2) {
        
        UIImage * image2 = [info objectForKey:UIImagePickerControllerEditedImage];
        
        _backImageView.image = image2;
        [_backBtn setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
        _backLabel.hidden = YES;
        backImage= image2;
        
        //self.backLabel.hidden = YES;
    }
    
    //从相机或相册页面返回
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)bindingBenClick{
    
    NSString *message = @"";
    if (fontImage == nil || backImage == nil) {
        
        message = @"请输入身份证正反面照片";
        
    }else if ([message isEqualToString:@""]){
        
         [self commitData];
        
    }else{
        
        [QMUITips showError:message inView:self.view hideAfterDelay:2];
    }

    
}
- (void)commitData{
    
    NSData *data1 = UIImageJPEGRepresentation(fontImage, 0.5f);
    NSData *data2 = UIImageJPEGRepresentation(backImage, 0.5f);
    NSArray *imageArray = [NSArray array];
    imageArray = @[fontImage,backImage];
    NSArray *imageName  = [NSArray array];
    imageName = @[data1,data2];
    
    //NSString *urlStr = [NSString stringWithFormat:@"%@%@",SSSCommomUrl,@"user/addIdentityBind"];
    //    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr] cachePolicy:0 timeoutInterval:5.0f];
    //
    //    [self setRequest:request];
    //
    //    [_manager POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
    //
    //        for (int index = 0; index<imageArray.count; index++) {
    //
    //            [formData appendPartWithFileData:imageName[index] name:[NSString stringWithFormat:@"%d",index] fileName:[NSString stringWithFormat:@"%d.jpg",index] mimeType:@"image/jpeg"];
    
    //        }
    //
    //    } progress:^(NSProgress * _Nonnull uploadProgress) {
    //
    //
    //
    //
    //    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    //
    //        ZDLog(@"-----iamge%@",responseObject);
    //
    //    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    //
    //        ZDLog(@"----%@",error.localizedDescription);
    //
    //    }];
    //
    
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:kConfigPath(kAddIdentity) parameters:nil constructingBodyWithBlock:
                                    ^(id<AFMultipartFormData> formData)
                                    {
                                        //                                        NSString *url = [[NSBundle mainBundle] pathForResource:@"bufda" ofType:@"jpg"];
                                        //
                                        //                                        [formData appendPartWithFileURL:[NSURL fileURLWithPath:url] name:@"files" fileName:@"filename.jpg" mimeType:@"image/*" error:nil];
                                        
                                        for (int index = 0; index<imageArray.count; index++) {
                                            
                                            [formData appendPartWithFileData:imageName[index] name:@"files" fileName:[NSString stringWithFormat:@"%d.jpg",index] mimeType:@"image/*"];
                                        }
                                        
                                    } error:nil];
    
    [request setValue:[SSSUserManager getUserModel].token forHTTPHeaderField:@"token"];
    
    _manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    _manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    NSURLSessionUploadTask *uploadTask;
    uploadTask = [_manager
                  uploadTaskWithStreamedRequest:request
                  progress:nil
                  completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                      
                      if (error) {
                          
                          NSLog(@"Error: %@", error);
                          [QMUITips showError:error.localizedDescription inView:self.view hideAfterDelay:2];
                          
                      } else {
                          
                          NSLog(@"----response%@   -----responseObject%@", response, responseObject);
                          [QMUITips showSucceed:@"提交成功" inView:self.view hideAfterDelay:2];
                      }
                  }];
    
    [uploadTask resume];
    
}
- (AFHTTPSessionManager *)manager{
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
        _manager.requestSerializer  = [AFHTTPRequestSerializer  serializer];
        _manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        [_manager.requestSerializer setValue:[SSSUserManager getUserModel].token forHTTPHeaderField:@"token"];
        _manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html", @"application/javascript", @"text/js", @"application/x-javascript", nil];
    }
    return _manager;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
